


import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';

import 'package:custom_social_share/custom_social_share.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:qr/qr.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:share_extend/share_extend.dart';
// import 'package:share_plus/share_plus.dart';
import 'package:smart_freezer/core/resources/app_config.dart';
import 'package:smart_freezer/core/resources/icon_names.dart';
import 'package:smart_freezer/core/resources/routers.dart';
import 'package:smart_freezer/core/service/api/app_api.dart';
import 'package:smart_freezer/core/service/service/result_data.dart';
import 'package:smart_freezer/core/utils/local_storage.dart';
import 'package:smart_freezer/core/utils/logs.dart';
import 'package:smart_freezer/core/utils/tr_extension.dart';
import 'package:smart_freezer/generated/locale_keys.g.dart';

import '../../../core/utils/file_util.dart';

class SettingPage extends StatefulWidget {
  const SettingPage({Key? key}) : super(key: key);

  @override
  State<SettingPage> createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {

  int _deviceNum = 0;

  List _dataList = [
    {"icon": IconNames.set_plkz, "title": LocaleKeys.set_up_controls.trc(), "content": LocaleKeys.set_up_tai.pluralc(0), "route": LCRouter.setting_choose_device},
    {"icon": IconNames.set_yy, "title": LocaleKeys.set_up_setting_language.trc(), "content": "", "route": LCRouter.setting_language},
    {"icon": IconNames.set_ms, "title": LocaleKeys.set_up_setting_mode.trc(), "content": LocaleKeys.set_up_mode_system.trc(), "route": LCRouter.setting_model},
    {"icon": IconNames.set_share, "title": LocaleKeys.login_share.trc(), "content": "${LocaleKeys.login_share.trc()} williams", "route": ""},
  ];

  var isDarkMode = LocalStorage.getThemeMode() == 1;

  GlobalKey repaintKey = GlobalKey();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _getDeviceList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 1,
        leadingWidth: 50,
        leading: InkWell(
          onTap: () {
            Get.back();
          },
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 9, 0, 9),
            child: Icon(Icons.arrow_back_ios_rounded), //Image.asset(IconNames.nav_back),
          ),
        ),
        title: Text(LocaleKeys.other_setting.trc(),),
        centerTitle: true,

        actions: [
          InkWell(
              onTap: (){
                Get.offNamed(LCRouter.login);
              },
              child: Container(
                  padding: EdgeInsets.fromLTRB(10, 0, 15, 0),
                  child: Icon(Icons.logout)
              )
          ),
        ],
      ),
      body: Container(
        width: MainCommon.screenWidth,
        padding: EdgeInsets.fromLTRB(10, 20, 10, 10),
        color: isDarkMode ? Colors.black : MainCommon.bgGreyColor,
        child: GridView(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              childAspectRatio: 1 / 1,
              crossAxisSpacing: 10,
              mainAxisSpacing: 10,
          ),
          children: List.generate(_dataList.length, (index) {
            final icon = _dataList[index]["icon"];
            final title = _dataList[index]["title"];
            final content = _dataList[index]["content"];
            final route = _dataList[index]["route"] as String;

            bool isChushi = LocalStorage.getRole() == "1" && index == 0;
            bool isDark = isDarkMode && isChushi;

            return InkWell(
              onTap: () {
                if(isChushi) return;

                if(route.isNotEmpty) {
                  Get.toNamed(route)?.then((value) {
                    setState((){
                      isDarkMode = LocalStorage.getThemeMode() == 1;
                    });
                  });
                  return;
                }
                if(title == LocaleKeys.login_share.trc()) {
                  _startShare();
                  return;
                }

              },
              child: Card(
                color: isDark ? Colors.grey.withOpacity(0.5) : (isChushi ? Colors.grey.shade300 : null),
                child: Container(
                  padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(height: 20,),
                      Image.asset(icon, width: 50,),
                      SizedBox(height: 20,),
                      Text(title, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 17),),
                      Text(content, style: TextStyle(color: Colors.grey, fontSize: 13),),
                    ],

                  ),
                ),
              ),
            );
          }),
        ),
      ),
    );
  }

  // 获取设备列表
  _getDeviceList() async {
    final params = {"page": "1", "limit": "100"};
    ResultData data = await AppApi.getInstance().getProductList(params);
    if(data.code == 0){
      final list = data.data as List;
      _deviceNum = list.length;
      setState(() {});

      final language = ["简体中文", "繁體中文", "English"][LocalStorage.getLanguageValue() - 1];
      _dataList = [
        {"icon": IconNames.set_plkz, "title": LocaleKeys.set_up_controls.trc(), "content": LocaleKeys.set_up_tai.pluralc(_deviceNum), "route": LCRouter.setting_choose_device},
        {"icon": IconNames.set_yy, "title": LocaleKeys.set_up_setting_language.trc(), "content": language, "route": LCRouter.setting_language},
        {"icon": IconNames.set_ms, "title": LocaleKeys.set_up_setting_mode.trc(), "content": LocaleKeys.set_up_mode_system.trc(), "route": LCRouter.setting_model},
        {"icon": IconNames.set_share, "title": LocaleKeys.login_share.trc(), "content": "${LocaleKeys.login_share.trc()} Williams", "route": ""},
      ];
    }
  }

  /// 开始分享
  _startShare() async {
    _showShareDialog();
    // CustomSocialShare().toAll("测试text https://www.baidu.com");

    // final box = context.findRenderObject() as RenderBox?;
    // ShareResult result = await Share.shareWithResult(
    //     "分享内容",
    //     subject: "",
    //     sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
    // );
    //
    // logs("result: ${result.status}");


    // ScaffoldMessenger.of(context).showSnackBar(SnackBar(
    //   content: Text("Share result: xxx"),  // ${result.status}
    // ));

    return;

    // 弹出编辑框
    showModalBottomSheet(
        context: context,
        builder: (_) {
          return Container(
            height: 200,
            child: Column(
              children: [
                Container(
                  width: MainCommon.screenWidth,
                  child: Text("分享到:", style: TextStyle(color: Colors.grey),),
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.all(15),
                ),
                Container(
                  height: 80,
                  padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: EasyRefresh.custom(
                      scrollDirection: Axis.horizontal,
                      slivers: [
                        SliverList(
                          delegate: SliverChildBuilderDelegate(
                                  (context, index) {
                                return InkWell(
                                  onTap: () {
                                    Get.back();
                                  },
                                  child: Container(
                                    padding: EdgeInsets.only(left: 10, right: 10),
                                    child: Column(
                                      children: [
                                        Image.asset(IconNames.share_weixin, width: 50,),
                                        Text("微信", style: TextStyle(fontSize: 15, color: Colors.grey),),
                                      ],
                                    ),
                                  ),
                                );
                              },
                              childCount: 1
                          ),
                        )
                      ]
                  ),
                ),
                Divider(
                  height: 1,
                  indent: 5,
                  endIndent: 5,
                ),
                InkWell(
                  onTap: () {
                    Get.back();
                  },
                  child: Container(
                    width: MainCommon.screenWidth,
                    padding: EdgeInsets.fromLTRB(10, 10, 10, 30),
                    child: Text(LocaleKeys.login_cancel.trc(), style: TextStyle(color: Colors.grey),),
                    alignment: Alignment.center,
                  ),
                )
              ],
            ),
          );
        }
    );
  }

  _showShareDialog() {

    final contentWidth = MainCommon.screenWidth * 0.8;
    final sharedUrl = Platform.isAndroid ? "https://www.pgyer.com/jO4Y" : "https://www.pgyer.com/jO4Y";

    showDialog(
      context: context,
      builder: (context){
        return AlertDialog(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          elevation: 0,
          backgroundColor: Colors.transparent,
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                width: contentWidth,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(10),
                  color: Colors.white,
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    SizedBox(height: 30,),

                    RepaintBoundary(
                      key: repaintKey,
                      child: Container(
                        width: contentWidth * 0.45,
                        height: contentWidth * 0.45,
                        decoration: BoxDecoration(
                          color: Colors.white,
                          // borderRadius: BorderRadius.circular(10)
                        ),
                        clipBehavior: Clip.antiAlias,
                        child: QrImageView(
                          data: sharedUrl,
                          version: QrVersions.auto, // 3, //QrVersions.auto,
                          padding: EdgeInsets.all(5),
                          gapless: false,
                          // embeddedImage: AssetImage(IconNames.order_money),  // 内嵌logo
                          // embeddedImageStyle: QrEmbeddedImageStyle(size: Size(30, 30)),
                        ),
                      ),
                    ),

                    SizedBox(height: 10,),
                    InkWell(
                      onTap: () async {
                        // 开始分享
                        RenderRepaintBoundary boundary =
                        repaintKey.currentContext?.findRenderObject() as RenderRepaintBoundary;
                        final image = await boundary.toImage();

                        ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
                        if(byteData == null) return;

                        final imgFilePath = await writeByteToImageFile(byteData);
                        ShareExtend.share(imgFilePath, "image");
                      },
                      child: Container(
                        child: Text(LocaleKeys.login_share.trc(), style: TextStyle(color: Colors.orange)),
                        height: 30,
                        width: 140,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(15),
                          border: Border.all(color: Colors.orange),
                        ),
                      ),
                    ),
                    SizedBox(height: 30,),

                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

}
